package com.lagou.homework03;

import java.util.concurrent.locks.ReentrantLock;

public class TicketThreadTest extends Thread {
    private static int ticketNumber = 100;

    public TicketThreadTest() { }
    public TicketThreadTest(int ticketNumber) { this.ticketNumber = ticketNumber; }
    public int getTicketNumber() { return ticketNumber; }
    public void setTicketNumber(int ticketNumber) { this.ticketNumber = ticketNumber; }
    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + "正在卖票中--");
        while (true){
            //添加同步锁,因为只有一个class，所以可以实现锁机制
            synchronized (TicketThreadTest.class) {
                if (ticketNumber > 0) {
                    ticketNumber--;
                    System.out.println("线程" + Thread.currentThread().getName() +"卖出一张票");
                    try {
                        //等待0.1秒
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("剩余票数："+ticketNumber);
                    System.out.println("--------------------------------------------");
                }else{
                    break;
                }
            }
        }
    }
    public static void main(String[] args) {

        TicketThreadTest att1 = new TicketThreadTest();
        att1.start();
        TicketThreadTest att2 = new TicketThreadTest();
        att2.start();
        TicketThreadTest att3 = new TicketThreadTest();
        att3.start();

        try {
            //等待线程结束
            att1.join();
            att2.join();
            att3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("票卖完了");



    }









}
